#!/bin/bash
#
# $Id$
#

#. /home/admin/monitoring/common/debug.h
#. $OPENARS_HOME/common/functions.h

SCRIPT_NAME=`basename $0`

usage()
{
cat <<EOF
Usage: `basename $0` [OPTION]
Known values for OPTION are:
     -h <HOST>  - only HOST
     -c <command>  - run commands
     -f <FILE>  - run commands from FILE (script)
     -a <FILE>  - attach the FILE
     -o <FILE>  - file for result, default output/$SCRIPT_NAME.out
EOF
}

command=
file_command=
file_attach=
file_out=
bk_flag=0
srvlist=

while [ $# -gt 0 ]
do
        case $1 in
        -h)	[ -z "$2" ] && { usage; exit 1; }
		srvlist=$2
                shift
		;;
        -c)
                [ -z "$2" ] && { usage; exit 1; }
                command=$2
                shift
                ;;
        -f)
		[ -z "$2" ] && { usage; exit 1; }
		file_command=$2
		[ ! -f "$file_command" ] && { echo "file $file_command not found. exit 1"; exit 1; }
		shift
		;;
        -a)
                [ -z "$2" ] && { usage; exit 1; }
                file_attach=$2
                #[ ! -f "$file_attach" ] && { echo "file $file_attach not found. exit 1"; exit 1; }
		shift        
		;;
        -o)
                [ -z "$2" ] && { usage; exit 1; }
                file_out=$2
		shift
                ;;
        -b|background)
                	bk_flag=1
			;;
        *)
                echo "unknown option $1"
                usage; exit 1
                ;;
        esac
        shift
done

[ ! -z "$file_command" -a ! -z "$command" ] && { usage; exit 1; }
[ -z "$file_command" -a -z "$command" ] && { usage; exit 1; }

remote_bin=bin
remote_dir=$$;
mkdir -p temp/$remote_dir || { echo "error create temp/$remote_dir. exit 1"; exit 1; }
mkdir -p output || { echo "error create \"output\". exit 1"; exit 1; }

if [ -z "$command" ]; then
        run_file=`basename $file_command`
        command="chmod +x $run_file; ./$run_file"
fi

[ -z "$file_out" ] && file_out=output/$SCRIPT_NAME.out
>$file_out

put_files=
put_files="$put_files $file_command"
put_files="$put_files $file_attach"
for i in $put_files
do
if [ ! -f "$i" ]; then
        question "file $i not found, continue?" res
        [ "$res" = "N" ] && exit 0
else
	cp $i temp/$remote_dir
fi

done

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

#[ -z "$srvlist" ] && srvlist=`get_hosts --control=YES`
echo "count hosts: `echo $srvlist | wc -w`"

for host in $srvlist
do
	echo -e "\n$host\n-------------" | tee -a $file_out
	scp -r temp/$remote_dir $user@$host:\$HOME/$remote_dir >/dev/null
		ssh $user@$host "mkdir -p temp; mv $remote_dir temp; cd temp/$remote_dir;
			$command; cd \$HOME; rm -r temp/$remote_dir" | tee -a $file_out
done

rm -r temp/$remote_dir

exit 0

